package cn.silver.framework.mybatis.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.silver.framework.core.model.DictModel;
import cn.silver.framework.log.annotation.Log;
import cn.silver.framework.log.enums.OperateEnums;
import cn.silver.framework.mybatis.bean.BusBean;
import cn.silver.framework.mybatis.domain.BusEntity;
import cn.silver.framework.mybatis.param.BusParam;
import cn.silver.framework.mybatis.service.IDataService;
import cn.silver.framework.openapi.model.Result;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class DataController<S extends IDataService<T, P, V>, T extends BusEntity, P extends BusParam, V extends BusBean>
        extends BusController<S, T, P, V> {

    @SaIgnore
    @GetMapping("/dict")
    @Operation(summary = "字典信息查询", description = "获取字典信息")
    public Result<List<DictModel>> listDict(@ModelAttribute P param) {
        List<V> resultList = this.baseService.selectList(param);
        List<DictModel> dictModels = resultList.stream().map(V::convertDict).collect(Collectors.toList());
        return Result.ok("查询成功", dictModels);
    }

    /**
     * 导出数据
     */
    @PostMapping("/export")
    @Operation(summary = "导出数据")
    @Log(operate = OperateEnums.OSS_EXPORT)
    public Result<Void> exportData(HttpServletResponse response, @ModelAttribute P param) {
        this.checkPermission("export");
        this.baseService.exportData(param, response);
        return Result.ok("数据导出成功");
    }

    @PostMapping("/template")
    @Operation(summary = "获取数据导入模板")
    @Log(operate = OperateEnums.OSS_IMPORT)
    public Result<Void> importTemplate(HttpServletResponse response) {
        this.checkPermission("import");
        this.baseService.importTemplate(response);
        return Result.ok("获取模板成功");
    }


    @PostMapping("/import")
    @Operation(summary = "导入数据")
    @Log(operate = OperateEnums.OSS_IMPORT)
    public Result<Void> importData(@RequestParam(value = "file") MultipartFile file, @ModelAttribute P param) {
        this.checkPermission("import");
        int success = this.baseService.importData(file, param);
        return Result.ok("导入成功,共导入" + success + "条数据");
    }
}
